/*
 * Copyright 2011 Alex Paréj.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mkdir.web.controller.admin;

import java.io.Serializable;
import java.util.Iterator;
import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.mkdir.ejb.FelhasznaloService;
import org.mkdir.model.Felhasznalo;
import org.mkdir.model.Szerepkor;
import org.primefaces.context.RequestContext;
import org.primefaces.model.DualListModel;

/**
 *
 * @author Alex Paréj
 */
@Named
@ViewScoped
public class EmailKuldesController implements Serializable {

    private static String EMAIL_KULDES_PREFIX = "window.location.href = 'mailto:";
    private DualListModel<Felhasznalo> felhasznalok;
    @Inject
    private FelhasznaloService felhasznaloService;

    @PostConstruct
    private void init() {
        felhasznalok = new DualListModel<Felhasznalo>();
        felhasznalok.setSource(felhasznaloService.getOsszesFelhasznalo());
    }

    public DualListModel<Felhasznalo> getFelhasznalok() {
        return felhasznalok;
    }

    public void setFelhasznalok(DualListModel<Felhasznalo> felhasznalok) {
        this.felhasznalok = felhasznalok;
    }

    public void emailKliensMegnyitasaListener() {
        RequestContext.getCurrentInstance().execute(getEmailKuldesScript());
    }

    public void adminokHozzaadasaListener() {
        Iterator<Felhasznalo> iterator = getFelhasznalok().getSource().iterator();
        while (iterator.hasNext()) {
            Felhasznalo f = iterator.next();
            if (felhasznaloService.isSzerepkorben(f, Szerepkor.ADMIN)) {
                if (!getFelhasznalok().getTarget().contains(f)) {
                    getFelhasznalok().getTarget().add(f);
                    iterator.remove();
                }
            }
        }
    }

    private String getOsszeallitottCimzettEmailek() {
        StringBuilder emailek = new StringBuilder();
        for (Felhasznalo f : felhasznalok.getTarget()) {
            emailek.append(f.getEmail());
            emailek.append(",");
        }
        return emailek.toString();
    }

    private String getEmailKuldesScript() {
        return EMAIL_KULDES_PREFIX +getOsszeallitottCimzettEmailek()+"';";
    }
}
